use actix_web::{ get, HttpResponse, Responder };
use rusqlite:: Connection;
use serde::{ Serialize, Deserialize };
use chrono::Local;

#[derive(Debug, Serialize, Deserialize)]
struct Log {
    id: i32,
    time: String,
    content: String,
    describe: String
}

#[get("/api/log/read")]
pub async fn read_log() -> impl Responder {
    
    let conn = Connection::open("./data/data.db").expect("log.rs /apt/log/read -> 数据库连接失败！");

    let mut stmt = conn.prepare("SELECT id, time, content, describe FROM log ORDER BY id DESC").expect("log.rs /api/log/read -> 查询失败！");

    let log_iter = stmt.query_map([], |row| {
        Ok(Log {
            id: row.get(0)?,
            time: row.get(1)?,
            content: row.get(2)?,
            describe: row.get(3)?,
        })
    }).expect("log.rs /api/log/read -> log_iter 迭代失败！");

    let mut logs = Vec::new();
    for log in log_iter {
        logs.push(log.unwrap());
    }

    HttpResponse::Ok().json(serde_json::to_string(&logs).unwrap())
}


pub fn write_log(c: &str, d: &str) {
    let conn = Connection::open("./data/data.db").expect("log.rs /api/log/write -> 数据库连接失败！");
    conn.execute(
        "INSERT INTO log (time, content, describe) VALUES (?1, ?2, ?3)",
        (Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),&c, &d)
    ).expect("log.rs /api/log/write -> 插入数据失败！");
}